import Vue from 'vue'
import VueRouter from 'vue-router'

// 路由懒加载
const Login = () =>
  import(/* webpackChunkName: "Login-Home" */ '../components/Login.vue')
const Home = () =>
  import(/* webpackChunkName: "Login-Home" */ '../components/Home.vue')

const Usres = () =>
  import(/* webpackChunkName: "Usres" */ '../components/users/Users.vue')

const Roles = () =>
  import(/* webpackChunkName: "Roles-Rights" */ '../components/power/Roles.vue')
const Rights = () =>
  import(
    /* webpackChunkName: "Rights-Rights" */ '../components/power/Rights.vue'
  )

const Cate = () =>
  import(/* webpackChunkName: "Cate-Params" */ '../components/goods/Cate.vue')
const Params = () =>
  import(/* webpackChunkName: "Cate-Params" */ '../components/goods/Params.vue')

const GoodsList = () =>
  import(
    /* webpackChunkName: "GoodsList-AddGoods-EidtGoods" */ '../components/goods/List.vue'
  )
const AddGoods = () =>
  import(
    /* webpackChunkName: "GoodsList-AddGoods-EidtGoods" */ '../components/goods/AddGoods.vue'
  )
const EidtGoods = () =>
  import(
    /* webpackChunkName: "GoodsList-AddGoods-EidtGoods" */ '../components/goods/EditGoods.vue'
  )

const Order = () =>
  import(/* webpackChunkName: "Order" */ '../components/order/Order.vue')

const Report = () =>
  import(/* webpackChunkName: "Report" */ '../components/report/Report.vue')

Vue.use(VueRouter)

const routes = [
  { path: '/', redirect: '/login' },
  { path: '/login', component: Login },
  {
    path: '/home',
    component: Home,
    redirect: '/reports',
    children: [
      //   { path: '/welcome', component: Welcome },
      { path: '/users', component: Usres },
      { path: '/roles', component: Roles },
      { path: '/rights', component: Rights },
      { path: '/categories', component: Cate },
      { path: '/params', component: Params },
      { path: '/goods', component: GoodsList },
      { path: '/goods/add/', component: AddGoods },
      { path: '/goods/edit/:goodsId', component: EidtGoods, props: true },
      { path: '/orders', component: Order },
      { path: '/reports', component: Report }
    ]
  }
]

// const originalPush = VueRouter.prototype.push
// VueRouter.prototype.push = function push(location) {
//   return originalPush.call(this, location).catch(err => err)
// }

const router = new VueRouter({
  routes
})

// 为路由对象添加 beforeEack 导航守卫
// to 将要访问的路径
// from 代表从那个路径跳转而来
// next 是一个函数，表示放行
router.beforeEach((to, from, next) => {
  // 如果用户访问登录页面，直接放行
  if (to.path === '/login') return next()
  // 从 sessionStorage 中获取 token 值
  const tokenStr = window.sessionStorage.getItem('token')
  // 如果没有 token，强制跳转到登录页面
  if (!tokenStr) return next('/login')
  next()
})

export default router
